package com.hsq.ndmall.order.listening;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hsq.ndmall.mq.constant.OrderRabbitMQ;
import com.hsq.ndmall.mq.dto.OrderMsgDto;
import com.hsq.ndmall.order.entity.OrderEntity;
import com.hsq.ndmall.order.service.OrderService;
import com.hsq.ndmall.order.utils.OrderUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author 黄四清
 * @version 1.0.0
 * @ClassName ConsumerRabbitMQ.java
 * @Description TODO  消费者，用于订单创建的30后被取消
 * @createTime 2021年09月06日 09:28:00
 */
@Component
@RabbitListener(queues = {OrderRabbitMQ.ORDER_CLOSE_QUEUE})
@Slf4j
public class ConsumerRabbitMQ {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitHandler
    public void classOrder(OrderMsgDto orderDto, Message message, Channel channel) throws IOException {
        log.info("我收到了消息{},要关闭", orderDto);
        // 查询订单状态,是否可关闭
        try {
            OrderEntity orderEntity = orderService.getById(orderDto.getOrderId());
            if (ObjectUtil.isNotEmpty(orderEntity)) {
                if (orderEntity.getOrderStatus().equals((int) OrderUtil.STATUS_CREATE)) {
                    // 未支付，关闭订单，
                    OrderEntity order = new OrderEntity();
                    order.setOrderStatus((int) OrderUtil.STATUS_AUTO_CANCEL);
                    order.setId(orderDto.getOrderId());
                    // 修改状态为103
                    boolean b = orderService.updateById(order);
                    if (!b) {
                        //修改失败
                        throw new RuntimeException("订单关闭失败");
                    } else {
                        // 修改成功
                        log.info("处理订单成功，关闭订单成功！{}", orderDto.getOrderSn());
                        if (orderEntity.getCouponPrice() != null && orderEntity.getCouponPrice() != new BigDecimal(0.00)) {  // 是否使用了优惠券
                            log.info("使用了优惠券，金额为：{}", orderEntity.getCouponPrice());
                            // 释放已消费的优惠券，返还已使用的优惠券
                            //  发送者
                            rabbitTemplate.convertAndSend(OrderRabbitMQ.ORDER_EVENT_EXCHANGE,
                                    OrderRabbitMQ.ORDER_RELEASE_OTHER_MSG,
                                    orderDto);
                        }

                    }
                    // 消费成功ACK
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                }
            } else {
                // 没有这个订单
                log.info("订单{}不存在", orderDto.getOrderSn());
            }
        } catch (Exception e) {
            log.info("========关闭订单异常，关闭消息返回到MQ队列==========");
            // 关闭订单失败，拒绝消息，重回MQ队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }


    }
}
